/**
 * CRM模块状态管理
 */

import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { Customer, Contact, Order, Review } from '@/types/crm'

export const useCrmStore = defineStore('crm', () => {
  // 当前选中的客户
  const currentCustomer = ref<Customer | null>(null)

  // 当前选中的联系人
  const currentContact = ref<Contact | null>(null)

  // 当前选中的订单
  const currentOrder = ref<Order | null>(null)

  // 当前选中的审核记录
  const currentReview = ref<Review | null>(null)

  // 客户列表
  const customerList = ref<Customer[]>([])

  // 订单列表
  const orderList = ref<Order[]>([])

  // 审核列表
  const reviewList = ref<Review[]>([])

  // 统计信息
  const stats = ref({
    totalCustomers: 0,
    totalOrders: 0,
    totalAmount: 0,
    pendingReviews: 0,
    cooperationCustomers: 0,
  })

  // 设置当前客户
  const setCurrentCustomer = (customer: Customer | null) => {
    currentCustomer.value = customer
  }

  // 设置当前联系人
  const setCurrentContact = (contact: Contact | null) => {
    currentContact.value = contact
  }

  // 设置当前订单
  const setCurrentOrder = (order: Order | null) => {
    currentOrder.value = order
  }

  // 设置当前审核记录
  const setCurrentReview = (review: Review | null) => {
    currentReview.value = review
  }

  // 更新客户列表
  const updateCustomerList = (list: Customer[]) => {
    customerList.value = list
  }

  // 更新订单列表
  const updateOrderList = (list: Order[]) => {
    orderList.value = list
  }

  // 更新审核列表
  const updateReviewList = (list: Review[]) => {
    reviewList.value = list
  }

  // 更新统计信息
  const updateStats = (newStats: any) => {
    stats.value = { ...stats.value, ...newStats }
  }

  // 重置状态
  const reset = () => {
    currentCustomer.value = null
    currentContact.value = null
    currentOrder.value = null
    currentReview.value = null
    customerList.value = []
    orderList.value = []
    reviewList.value = []
    stats.value = {
      totalCustomers: 0,
      totalOrders: 0,
      totalAmount: 0,
      pendingReviews: 0,
      cooperationCustomers: 0,
    }
  }

  return {
    currentCustomer,
    currentContact,
    currentOrder,
    currentReview,
    customerList,
    orderList,
    reviewList,
    stats,
    setCurrentCustomer,
    setCurrentContact,
    setCurrentOrder,
    setCurrentReview,
    updateCustomerList,
    updateOrderList,
    updateReviewList,
    updateStats,
    reset,
  }
})
